<?php
namespace app\api\controller\market;
use app\api\controller\Controller;
use app\api\model\Dealer as DealerModel;
use app\api\model\User as UserModel;
use app\api\model\Setting as SettingModel;
use app\common\library\helper;
use think\Image;

/**
 * 分销中心管理
 */
class Dealer extends Controller
{	
    /**
     * 首页
     */
    public function index()
    {
		// 当前用户信息
        $userInfo = $this->getUser();
		$dealer = SettingModel::getItem('dealer');
		$userInfo['extract_money'] = helper::number2(0);	//可提现
		if($userInfo['commission']>=$dealer['min_money']){
			$userInfo['extract_money'] = helper::number2(intval($userInfo['commission']));	//可提现
		}
		$settlement_money = DealerModel::where([
			'user_id' => $userInfo['user_id'],
			'mode' => 20,
			'take_status' => 20
		])->sum('price');
		$in_money = DealerModel::where([
			'user_id' => $userInfo['user_id'],
			'mode' => 20,
			'take_status' => 10
		])->sum('price');
		$userInfo['settlement_money'] = helper::number2($settlement_money);	//已提现
		$userInfo['in_money'] = helper::number2($in_money);	//提现中
        return $this->renderSuccess(compact('userInfo'));
    }
	
	/**
     * 一键提现
     */
    public function team()
    {
		// 当前用户信息
        $userInfo = $this->getUser();
		$model = new UserModel;
		$list = $model->getApiList($userInfo['user_id']);
		$all = $model->getApiAll($userInfo['user_id']);
		return $this->renderSuccess(compact('list','all'));
    }
	
	/**
     * 一键提现
     */
    public function take($extract_money)
    {
		// 当前用户信息
        $userInfo = $this->getUser();
		$model = new DealerModel;
		if($model->add($userInfo['user_id'],$extract_money)){
			return $this->renderSuccess([],'申请成功，等待审核');
		}
		$error = $model->getError() ?: '申请失败';
        return $this->renderError($error);
    }
	
	/**
     * 交易记录
     */
    public function lists($mode)
    {
		// 当前用户信息
        $userInfo = $this->getUser();
        $model = new DealerModel;
        $list = $model->getList($mode);
		if($mode==10){
			for($n=0;$n<sizeof($list);$n++){
				if($list[$n]['user']['recommender']==$userInfo['user_id']){
					$list[$n]['rank'] = '一级';
				}else{
					$list[$n]['rank'] = '二级';
				}
			}
		}
        return $this->renderSuccess(compact('list'));
    }
	
	/**
     * 首页
     */
    public function poster()
    {
		// 当前用户信息
        $userInfo = $this->getUser();
		header('Content-Type: image/png');//输出协议头
		$bg_path = './assets/poster/'.$this->wxapp_id .'.png';//背景图
		if(!file_exists($bg_path)){
			//如果背景图不存在
			$poster = 'no';
			//生成海报
			return $this->renderSuccess(compact('poster'));  
		}
		//生成二维码
		$this->qrCode($userInfo);
		
		//生成临时缩略图
		$url = './assets/poster/temp/'.'user'.$userInfo['user_id'].'.png';
		$image = Image::open($url);//读取原图
		$image->thumb(300,300)->save($url);
		yuan_img($url);
		
		$user_head = './assets/poster/temp/'.'user_head'.$userInfo['user_id'].'.png';
		$head_t = imagecreatefromstring(file_get_contents($userInfo['avatarUrl']));//读取用户头像
		imagepng($head_t,$user_head);
		
		$head_img = Image::open($user_head);//读取原图
		$head_img->thumb(120,120)->save($user_head);
		
		//创建图片的实例
		$bg = imagecreatefromstring(file_get_contents($bg_path));//读取背景图片数据流
		$logo = imagecreatefromstring(file_get_contents($url));//读取二维码数据流
		$head = imagecreatefromstring(file_get_contents($user_head));//读取用户头像
		//获取水印图片的宽高
		list($src_w, $src_h) = getimagesize($url);
		
		//将水印图片复制到目标图片上，最后个参数100是设置透明度，这里实现不透明效果
		//imagecopymerge($bg, $logo, 1360, 833, 0, 0, $src_w, $src_h, 100);
		//如果水印图片本身带透明色，则使用imagecopy方法
		imagecopy($bg, $logo, 225, 380, 0, 0, $src_w, $src_h);
		//获取水印图片的宽高
		list($src_w, $src_h) = getimagesize($user_head);
		imagecopy($bg, $head, 315, 30, 0, 0, $src_w, $src_h);

		//设置水印文字颜色
		$col = imagecolorallocatealpha($bg,255,255,255,0);
		//添加水印文字
		$nickName = $userInfo['nickName'].'，向您推荐';
		$b = strlen($nickName);//计算有几个汉子
		$x = (750-$b*7)/2;
		imagettftext($bg,15,0,$x,175,$col,WEB_PATH."assets/plugins/fonts/msyh.ttf",$nickName);
		
		imagepng($bg,'assets/poster/user/'.$userInfo['user_id'].'.png');
		//将数据进行销毁
		imagedestroy($bg);
		imagedestroy($logo);
		imagedestroy($head);
		imagedestroy($head_t);
		$poster = web_url().'assets/poster/user/'.$userInfo['user_id'].'.png';
		//生成海报
		 return $this->renderSuccess(compact('poster'));
    }
	
	/**
     * 生成二维码
     */
	private function qrCode($user)
	{
		$scene = 'user,'.$user['user_id'];
		$access_token = getAccessToken();
		$url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='.$access_token;
		$data = '{"scene":"'.$scene.'"}';
		$result = http_request($url,$data);
		if(isset($result['errcode']) AND $result['errcode']!=0){
			$this->error = '生成分享码错误，code：'.$result['errcode'].'，msg:'.$result['errmsg'];
			return false;
		}
		file_put_contents('assets/poster/temp/user'.$user['user_id'].'.png',$result); //获取的二维码数据存储到指定的文件
		return true;
	}
	
}
